<template>
    <div class="login">
        <div class="div_login">
            <div class="login_img"></div>
            <input type="text" id="name" v-model="name" />
            <input type="password" id="key" v-model="key" />
            <button id="login" @click="login()">登录</button>
            <button id="goRegister" @click="goRegister()">去注册</button>
        </div>
    </div>
</template>

<script lang="ts">
import { Vue } from 'vue-class-component';
import { UserApi } from '@/api/user';
import { useStore } from 'vuex';

export default class Login extends Vue {
    user_store = useStore();
    name = '';
    key = '';

    async login() {
        if (this.name == '' || this.key == '') {
            alert('请输入登录信息');
            return;
        }
        const res = await UserApi.login({
            user_name: this.name,
            password: this.key,
        });
        if (res.code == 0) {
            sessionStorage.setItem('token', res.data.token);
            // 用户信息保存到vuex和localStorage
            let json_msg = JSON.stringify(res.data.user[0]);
            // console.log(json_msg);
            localStorage.setItem('data', json_msg);
            this.user_store.dispatch('setUser', res.data.user[0]);
            this.$router.push('/user');
        } else {
            alert('用户名或密码错误');
        }
    }
    goRegister() {
        this.$router.push('/register');
    }
}
</script>

<style lang="less" scoped>
.login {
    width: 100vw;
    height: 100vh;
    position: relative;
    background-color: whitesmoke;
}
.login_img {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    position: absolute;
    transform: translate(-50%, -50%);
    top: 0;
    left: 50%;
    background-image: url(../../public/img/static/login.png);
    background-repeat: no-repeat;
    background-position: 5px;
    background-size: 50px 50px;
    box-shadow: 3px 3px 10px #888888;
}
.div_login {
    width: 30%;
    min-width: 460px;
    height: 250px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: white;
    border-radius: 5px;
    box-shadow: 3px 3px 10px #888888;
}
.div_login input {
    width: 80%;
    height: 30px;
    margin: 40px 43px 0 43px;
    border: 1px solid black;
    border-radius: 5px;
}
#name {
    background-image: url(../../public/img/static/name.png);
    background-repeat: no-repeat;
    background-position: 0;
    text-indent: 35px;
}
#key {
    background-image: url(../../public/img/static/key.png);
    background-repeat: no-repeat;
    background-position: 0;
    text-indent: 35px;
}
#login,
#goRegister {
    width: 40%;
    height: 30px;
    margin: 35px 0;
    position: absolute;
    bottom: 10px;
}
#login {
    left: 43px;
}
#goRegister {
    right: 43px;
}
</style>
